<template>
  <div class="app-container">
    <el-header>
      <el-button @click="handleCreate" type="primary">创建</el-button>
    </el-header>
    <el-table
      :data="list"
      border
      style="width: 100%"
      highlight-current-row
      v-loading="listLoading"
      element-loading-text="loading"
      max-height="400"
    >
      <el-table-column prop="title" label="标题" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button @click="handleEeit(scope.row)" type="primary" size="small">编辑</el-button>
          <el-button @click="handleDelItem(scope.row._id)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-footer>
    <el-pagination
      :page-size=paginationDate.rows
      :total=paginationDate.total
      :current-page=paginationDate.cuurentPage
      :page-sizes=paginationDate.pageSizes
      layout='total, prev, pager, next, jumper, sizes, slot'
      @size-change='handleSizeChange'
      @current-change='handleCurrentChange'
      style="line-height: 30px; min-width:300px;"
    >
      <i @click="handReload" class="el-icon-refresh"></i>
    </el-pagination>
  </el-footer>
    <el-dialog
      :visible.sync="dialogVIsible"
      :title = "dialogTitle"
    >
      <el-form :rules="rules" ref="formData" :model="formData" label-position="left">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="链接" v-show="false">
          <el-input v-model="formData.url" v-show="false"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <img-heper id="imgHeaper" class="img-heaper" :src="formData.url" @imgheaperchange="handleImgHeaperChange"/>
        </el-form-item>
        <el-form-item label="ID"  v-show="false">
          <el-input v-model="formData._id"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getItems, updateOrAddItem, delItem } from '@/cloudbaseapi/cloudbase-hdimg'
import { cloud_md5, loadingFull } from '@/cloudbaseapi/cloudbase-api'
import ImgHeper from '@/components/ImgHeper/index'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      dialogVIsible: false,
      list: [],
      listLoading: false,
      dialogTitle: '编辑',
      state: '',
      paginationDate: {
        total: 10,
        cuurentPage: 1,
        rows: 10,
        pageSizes: [10, 20, 30, 50]
      },
      formData: {
        _id: '',
        title: '',
        url: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      }
    }
  },
  async mounted() {
    await this.handGetItems()
  },
  methods: {
    async handGetItems(limit = 10, page = 1) {
      this.listLoading = true
      const items = await getItems(limit, page)
      this.list = items['data']
      this.paginationDate.total = items['total']
      setTimeout(() => {
        this.listLoading = false
      }, 1000)
    },
    handleEeit(row) {
      this.dialogTitle = '编辑'
      this.state = 'edit'
      this.dialogVIsible = true
      this.initFormData(row)
    },
    handleCreate() {
      this.dialogTitle = '创建'
      this.state = 'create'
      this.dialogVIsible = true
      this.initFormData()
    },
    handleSizeChange(val) {
      this.handGetItems(val, this.paginationDate.cuurentPage)
      this.paginationDate.rows = val
    },
    handleCurrentChange(val) {
      this.handGetItems(this.paginationDate.rows, val)
      this.paginationDate.cuurentPage = val
    },
    handReload() {
      this.handGetItems(this.paginationDate.rows, this.paginationDate.cuurentPage)
    },
    initFormData(row = null) {
      if (row) {
        this.formData.title = row.title
        this.formData._id = row._id
        this.$nextTick(() => {
          this.formData.url = row.url
        })
      } else {
        this.formData.title = ''
        this.formData._id = cloud_md5(new Date().getTime())
        this.$nextTick(() => {
          this.formData.url = ''
        })
      }
    },
    handleImgHeaperChange(url) {
      this.$nextTick(() => {
        this.formData.url = url
      })
    },
    submit() {
      this.$refs['formData'].validate((vaild) => {
        const load = loadingFull()
        if (vaild) {
          if(this.formData.url === '') {
            setTimeout(() => {
              load.close()
            }, 500)
            Message({
              message: '请上传图片',
              type: 'error',
              duration: 2000
            })
          } else {
            updateOrAddItem(this.formData, this.state).then(res => {
              console.log(res)
              setTimeout(() => {
                load.close()
                this.handReload()
              }, 500)
              Message({
                message: '提交成功',
                type: 'success',
                duration: 2000
              })

            }).catch(err => {
              console.log(err)
              Message({
                message: '提交失败',
                type: 'error',
                duration: 2000
              })
            })
          }
        } else {
          setTimeout(() => {
            load.close()
          }, 500)
          Message({
            message: '表单填写不规范请按要求填',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleDelItem(id) {
      const load = loadingFull()
      delItem(id).then(res => {
        this.$nextTick(() => {
          load.close()
          this.handReload()
        })
        Message({
          message: '删除成功',
          type: 'success',
          duration: 2000
        })

      }).catch(err => {
        this.$nextTick(() => {
          load.close()
          this.handReload()
        })
        Message({
          message: '删除失败',
          type: 'error',
          duration: 2000
        })
      })
    }
  },
  components: {
    ImgHeper
  }
}
</script>

<style scoped lang="scss">
  .img-heaper{
    margin-left:90px;
  }
</style>
